package app

import (
	"encoding/json"
	"fmt"
	"math"
	"reflect"
	"strconv"
	"strings"
	"time"

	. "gitee.com/tomatomeatman/golang-repository/bricks/model"
	. "gitee.com/tomatomeatman/golang-repository/bricks/utils/function/data"
	. "gitee.com/tomatomeatman/golang-repository/bricks/utils/function/system"
	. "gitee.com/tomatomeatman/golang-repository/bricks/utils/gorm"
	Log "github.com/cihub/seelog"
	"github.com/gin-gonic/gin"
)

type ModuleUtil struct{}

/**
 * 取模块数据实体,并创建新实例
 * control 控制层
 */
func (mu ModuleUtil) GetModuleEntity(control interface{}) interface{} {
	name := reflect.TypeOf(control).String()

	iSt := strings.Index(name, ".")
	if iSt > -1 {
		name = name[iSt+1:]
	}

	if strings.HasSuffix(name, "Controller") {
		name = strings.Replace(name, "Controller", "_ModuleEntity", 1)
	} else {
		name = name + "_ModuleEntity"
	}

	entity := GlobalVariable{}.Get(name)
	if nil != entity {
		return entity
	}

	controlRV := reflect.ValueOf(control) // 取得control变量的指针

	moduleEntity := controlRV.Elem().FieldByName("ModuleEntity")
	if !moduleEntity.IsValid() {
		return MsgEmity{}.Err(9001, "未设置模块数据实体")
	}

	entity = reflect.New(moduleEntity.Type()).Elem() //New()创建一个指向st类型的指针(本身为val类型), Elem()获取指针指向的vl的值

	GlobalVariable{}.RegisterVariable(name, entity)

	return entity
}

/**
 * 按模块数据实体创建新实例
 * control 控制层
 */
func (mu ModuleUtil) NowModuleEntity(control interface{}) interface{} {
	controlRV := reflect.ValueOf(control) // 取得control变量的指针

	moduleEntity := controlRV.Elem().FieldByName("ModuleEntity")
	if !moduleEntity.IsValid() {
		return MsgEmity{}.Err(9001, "未设置模块数据实体")
	}

	entity := reflect.New(moduleEntity.Type()).Elem() //New()创建一个指向st类型的指针(本身为val类型), Elem()获取指针指向的vl的值

	return entity
}

/**
 * 取对应模块业务实体
 * control 控制层
 */
func (mu ModuleUtil) GetService(name string) interface{} {
	return GlobalVariable{}.Get(name)
}

/**
 * 取对应模块业务实体
 * control 控制层
 */
func (mu ModuleUtil) GetModuleService(control interface{}) interface{} {
	name := reflect.TypeOf(control).String()

	iSt := strings.Index(name, ".")
	if iSt > -1 {
		name = name[iSt+1:]
	}

	if strings.HasSuffix(name, "Controller") {
		name = strings.Replace(name, "Controller", "_ModuleService", 1)
	} else {
		name = name + "_ModuleService"
	}

	service := GlobalVariable{}.Get(name)
	if nil != service {
		return service
	}

	controlRV := reflect.ValueOf(control) // 取得control变量的指针

	moduleService := controlRV.Elem().FieldByName("ModuleService")
	if !moduleService.IsValid() {
		return MsgEmity{}.Err(9002, "未设置模块业务实体")
	}

	service = reflect.New(moduleService.Type()).Elem().Interface()

	GlobalVariable{}.RegisterVariable(name, service)

	return service
}

// /**
//  * 取对应模块业务控制参数
//  * control 控制层
//  */
// func (mu ModuleUtil) GetModuleEnable(control interface{}) int {
// 	name := reflect.TypeOf(control).String()

// 	iSt := strings.Index(name, ".")
// 	if iSt > -1 {
// 		name = name[iSt+1:]
// 	}

// 	if strings.HasSuffix(name, "Controller") {
// 		name = strings.Replace(name, "Controller", "_ModuleEnable", 1)
// 	} else {
// 		name = name + "_ModuleEnable"
// 	}

// 	enable := GlobalVariable{}.Get(name)
// 	if nil != enable {
// 		return 9111110 //如果没有设置, 直接设置为全部禁止
// 	}

// 	return enable.(int)
// }

/**
 * 取对应模块业务控制参数
 * control 控制层
 */
func (mu ModuleUtil) GetModuleEnable(moduleName string) int {
	enable := GlobalVariable{}.Get(moduleName + "_ModuleEnable")
	if nil == enable {
		return 9111110 //如果没有设置, 直接设置为全部禁止
	}

	return enable.(int)
}

/**
 * 控制开关,6个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆
 * 其中前5个为'是否仅创建者可操作'后续为其它控制开关
 * @param i 位数,从左到右从1开始
 * @return
 */
func (mu ModuleUtil) EnableTag(moduleName string, i int) bool {
	enable := GlobalVariable{}.Get(moduleName + "_ModuleEnable")
	if nil == enable {
		return false //如果没有设置, 直接设置为禁止
	}

	data := enable.(int)
	result := data / int(math.Pow10(i-1)) % 10

	return result != 1 //1代表限制,非1才是不限制
}

/**
 * 控制开关,6个数的控制分别是:删除、修改、查询、导出、统计、步骤值可逆
 * 其中前5个为'是否仅创建者可操作'后续为其它控制开关
 * @param i 位数,从左到右从1开始
 * @return
 */
func (mu ModuleUtil) EnableFind(moduleName string) bool {
	return mu.EnableTag(moduleName, 6)
}

// 取当前用户
func (mu ModuleUtil) CurrentLoginUserId(ctx *gin.Context) string {
	header := ctx.Request.Form
	return header.Get("sLoginUserId")
}

// 取新ID
func (mu ModuleUtil) GetNewId(iLength int, sTableName string) string {
	service := ModuleUtil{}.GetService("TableKeyService")
	if nil == service {
		Log.Error("未找到对应的'TableKeyService'")
		return "0"
	}

	result := ReflectUtils{}.DoMethod(service, "GetNewId", iLength, sTableName)
	me := result[0].Interface()

	return me.(string)
}

// 分页数据查询部分语句,在分页查询数据及 数据搜索时使用
// 返回 findByPageCountSql, findByPageSql, params
func (mu ModuleUtil) GetFindByPageSelectSql(currentUser string, entity interface{},
	findByPageParam FindByPageParam, onlyCreator bool) (string, string, map[string]interface{}) {
	conditionMap := map[string]interface{}{}                       //普通条件
	conditionRangeStMap := map[string]interface{}{}                //范围条件
	conditionRangeEdMap := map[string]interface{}{}                //范围条件
	conditionArrayMap := map[string]string{}                       //数组条件
	conditionLikeMap := []string{}                                 //模糊查询字段
	sLikeStr := strings.TrimSpace(findByPageParam.GsLikeStr)       //全文检索条件
	sLikeDateSt := strings.TrimSpace(findByPageParam.GsLikeDateSt) //模糊查询记录修改时间范围条件-开始
	sLikeDateEd := strings.TrimSpace(findByPageParam.GsLikeDateEd) //模糊查询记录修改时间范围条件-结束

	params := map[string]interface{}{}

	var appendFieldSql strings.Builder
	var dictionarySql strings.Builder
	var oTherJoin map[string]string

	var s reflect.Type
	typeOf := reflect.TypeOf(entity)  //通过反射获取type定义
	if typeOf.Kind() == reflect.Ptr { //是否指针类型
		s = reflect.TypeOf(entity).Elem() //通过反射获取type定义
	} else {
		s = entity.(reflect.Value).Type() //通过反射获取type定义
	}

	tableInfo := TableInfo{}.GetByEntity(entity)
	sDbName := SqlFactory{}.GetDbName(tableInfo.GsDbName)
	sTableName := tableInfo.GsTableName
	//sMainTableKeyName := tableInfo.GsKeyName

	if (nil != findByPageParam.Gcondition) && (len(findByPageParam.Gcondition.(map[string]interface{})) > 0) {
		condition := findByPageParam.Gcondition.(map[string]interface{})
		for key, val := range condition {
			_, ok := s.FieldByName(key) //直接以字段名作为条件的(即不管是否以St或Ed结尾,都不属于范围条件)
			if ok {
				conditionMap[key] = val //明确值的字符串/日期/数字等都直接加入查询条件
				params[key] = val
				continue
			}

			if strings.HasSuffix(key, "St") { //以St结尾
				temp := key[0 : len(key)-2]  //去掉结尾
				_, ok := s.FieldByName(temp) //直接以字段名作为条件的(即不管是否以St或Ed结尾,都不属于范围条件)
				if ok {
					conditionRangeStMap[temp] = val //明确值的字符串/日期/数字等都直接加入查询条件
					params[key] = val
				}
				continue
			}

			if strings.HasSuffix(key, "Ed") { //以Ed结尾
				temp := key[0 : len(key)-2]  //去掉结尾
				_, ok := s.FieldByName(temp) //直接以字段名作为条件的(即不管是否以St或Ed结尾,都不属于范围条件)
				if ok {
					conditionRangeEdMap[temp] = val //明确值的字符串/日期/数字等都直接加入查询条件
					params[key] = val
				}
				continue
			}

			valType := reflect.TypeOf(val)
			if (strings.HasSuffix(key, "Array")) && (nil != val) && (strings.HasPrefix(valType.String(), "[]")) { //以Array结尾,并且属于数组类型
				temp := key[0 : len(key)-len("Array")] //去掉结尾
				_, ok := s.FieldByName(temp)           //直接以字段名作为条件的(即不管是否以St或Ed结尾,都不属于范围条件)
				if !ok {
					continue //字段名不存在
				}

				var sb strings.Builder
				sb.WriteString("(@@@@_@@@@")

				valArray := val.([]interface{})
				if strings.Contains("/int/int64/long/decimal/float64/", valType.String()) {
					for _, v := range valArray {
						sb.WriteString(",")
						sb.WriteString(fmt.Sprintf("%v", v))
					}
				} else {
					for _, v := range valArray {
						sb.WriteString(",'")
						sb.WriteString(fmt.Sprintf("%v", v))
						sb.WriteString("'")
					}
				}

				sb.WriteString(")")
				conditionArrayMap[temp] = strings.Replace(sb.String(), "@@@@_@@@@,", "", 1)

				continue
			}
		}
	}

	if "" != sLikeStr {
		var dLikeDateSt time.Time
		var dLikeDateEd time.Time

		if "" != sLikeDateSt {
			dLikeDateSt = TimeUtil{}.ToDate(sLikeDateSt)
		} else {
			dLikeDateSt = TimeUtil{}.AddDay(time.Now(), -7)
		}

		if "" != sLikeDateEd {
			dLikeDateEd = TimeUtil{}.ToDate(sLikeDateEd)
		} else {
			dLikeDateEd = time.Now()
		}

		params["dLikeDateSt"] = dLikeDateSt
		params["dLikeDateEd"] = dLikeDateEd
	}

	for i := 0; i < s.NumField(); i++ {
		//--非匿名属性--//
		if !s.Field(i).Anonymous {
			str := s.Field(i).Tag.Get("dataInfo")
			if "" == str {
				continue //没有设置dataInfo则不能参与
			}

			var dataInfo DataInfo
			json.Unmarshal([]byte(str), &dataInfo)

			if "" != findByPageParam.GsLikeStr {
				if !strings.Contains("/id/uId/sId/sCreator/dCreateDate/sModifieder/dModifiedDate/iState/iSetp/iIndex/iVersion/", dataInfo.GsName) &&
					((dataInfo.GsDbFileType == "varchar") || (dataInfo.GsDbFileType == "char")) {
					conditionLikeMap = append(conditionLikeMap, dataInfo.GsTableName+"."+dataInfo.GsName)
				}
			}

			f, d := mu.GetFindByPageSelectSqlByField(dataInfo, sTableName, s.Field(i).Name, oTherJoin)
			if "" != f {
				appendFieldSql.WriteString(f)
			}

			if "" != d {
				dictionarySql.WriteString(d)
			}

			continue
		}

		//-- 匿名属性需要进一步向下探索 --//
		anonyTagInfo := DataInfo{}.GetAnonyTagInfo(s.Field(i))
		if nil == anonyTagInfo {
			continue
		}

		for key := range anonyTagInfo {
			str := anonyTagInfo[key]
			if "" == str {
				continue
			}

			var dataInfo DataInfo
			json.Unmarshal([]byte(str), &dataInfo)

			if "" != findByPageParam.GsLikeStr {
				if !strings.Contains("/id/uId/sId/sCreator/dCreateDate/sModifieder/dModifiedDate/iState/iSetp/iIndex/iVersion/", dataInfo.GsName) &&
					((dataInfo.GsDbFileType == "varchar") || (dataInfo.GsDbFileType == "char")) {
					conditionLikeMap = append(conditionLikeMap, dataInfo.GsTableName+"."+dataInfo.GsName)
				}
			}

			f, d := mu.GetFindByPageSelectSqlByField(dataInfo, sTableName, s.Field(i).Name, oTherJoin)
			if "" != f {
				appendFieldSql.WriteString(f)
			}

			if "" != d {
				dictionarySql.WriteString(d)
			}
		}
	}

	var defaultOrderSql strings.Builder
	defaultOrderSql.WriteString(" ORDER BY @@@@_@@@@")

	if tableInfo.GbHasIndex {
		defaultOrderSql.WriteString(",")
		defaultOrderSql.WriteString("${sTableName}.")
		defaultOrderSql.WriteString(TableIndexName)
	}

	if tableInfo.GbHasModifiedDate {
		defaultOrderSql.WriteString(",")
		defaultOrderSql.WriteString("${sTableName}.")
		defaultOrderSql.WriteString(TableModifiedDateName)
		defaultOrderSql.WriteString(" DESC")
	}

	var vFindByPageWhere strings.Builder
	if onlyCreator && (tableInfo.GbHasCreator) {
		currentLoginUserId := currentUser
		if !strings.Contains("/00000000/00000001/", currentLoginUserId) {
			vFindByPageWhere.WriteString("AND ${sTableName}.CreatorName = '")
			vFindByPageWhere.WriteString(currentLoginUserId)
			vFindByPageWhere.WriteString("')")
		}
	}

	if len(conditionMap) > 0 {
		for key, val := range conditionMap {
			if strings.Contains(fmt.Sprintf("%v", val), "%") {
				vFindByPageWhere.WriteString(" AND ${sTableName}.")
				vFindByPageWhere.WriteString(key)
				vFindByPageWhere.WriteString(" LIKE @")
				vFindByPageWhere.WriteString(key)
			} else {
				vFindByPageWhere.WriteString(" AND ${sTableName}.")
				vFindByPageWhere.WriteString(key)
				vFindByPageWhere.WriteString(" = @")
				vFindByPageWhere.WriteString(key)
			}

			params[key] = val
		}
	}

	if len(conditionRangeStMap) > 0 {
		for key, val := range conditionRangeStMap {
			if "" != fmt.Sprintf("%v", val) {
				vFindByPageWhere.WriteString(" AND ${sTableName}.")
				vFindByPageWhere.WriteString(key)
				vFindByPageWhere.WriteString(" >= @")
				vFindByPageWhere.WriteString(key)
				vFindByPageWhere.WriteString("St")
			}
		}
	}

	if len(conditionRangeEdMap) > 0 {
		for key, val := range conditionRangeEdMap {
			if "" != fmt.Sprintf("%v", val) {
				vFindByPageWhere.WriteString(" AND ${sTableName}.")
				vFindByPageWhere.WriteString(key)
				vFindByPageWhere.WriteString(" <= @")
				vFindByPageWhere.WriteString(key)
				vFindByPageWhere.WriteString("Ed")
			}
		}
	}

	if len(conditionArrayMap) > 0 {
		for key, val := range conditionArrayMap {
			if "" == fmt.Sprintf("%v", val) {
				continue
			}

			vFindByPageWhere.WriteString(" AND ${sTableName}.")
			vFindByPageWhere.WriteString(key)
			vFindByPageWhere.WriteString(" IN (")
			vFindByPageWhere.WriteString(val)
			vFindByPageWhere.WriteString(")")
		}
	}

	if ("" != sLikeStr) && (len(conditionLikeMap) > 0) {
		if tableInfo.GbHasModifiedDate {
			vFindByPageWhere.WriteString(" AND ${sTableName}.dModifiedDate >= @dLikeDateSt")
			vFindByPageWhere.WriteString(" AND ${sTableName}.dModifiedDate <= @dLikeDateEd")
		}

		vFindByPageWhere.WriteString(" AND (@@@@_@@@@")

		for _, key := range conditionLikeMap {
			vFindByPageWhere.WriteString(" OR (")
			vFindByPageWhere.WriteString(key)
			vFindByPageWhere.WriteString(" LIKE CONCAT('%', @sLikeStr, '%'))")
		}

		vFindByPageWhere.WriteString(")")

		params["sLikeStr"] = sLikeStr
	}

	var findByPageCountSql strings.Builder
	findByPageCountSql.WriteString("SELECT COUNT(1) AS iCount FROM ")
	findByPageCountSql.WriteString(sDbName)
	findByPageCountSql.WriteString(sTableName)

	if 0 != vFindByPageWhere.Len() {
		findByPageCountSql.WriteString(" WHERE ")
		findByPageCountSql.WriteString(vFindByPageWhere.String())
	}

	result0 := strings.Replace(findByPageCountSql.String(), "${sTableName}", sTableName, -1)
	result0 = strings.Replace(result0, "@@@@_@@@@ OR ", "", -1)
	result0 = strings.Replace(result0, " WHERE    AND ", " WHERE ", -1)
	result0 = strings.Replace(result0, " WHERE   AND ", " WHERE ", -1)
	result0 = strings.Replace(result0, " WHERE  AND ", " WHERE ", -1)
	result0 = strings.Replace(result0, " WHERE AND ", " WHERE ", -1)

	var findByPageSql strings.Builder
	findByPageSql.WriteString("SELECT ")
	findByPageSql.WriteString(appendFieldSql.String())
	findByPageSql.WriteString(" ${sTableName}.* ")
	findByPageSql.WriteString(" FROM ${sDbName}${sTableName} AS ${sTableName} ")

	if "" != dictionarySql.String() {
		findByPageSql.WriteString(dictionarySql.String())
	}

	if 0 != vFindByPageWhere.Len() {
		findByPageSql.WriteString(" WHERE ")
		findByPageSql.WriteString(vFindByPageWhere.String())
	}

	if len(findByPageParam.Gorders) > 0 {
		findByPageSql.WriteString(" ORDER BY ")
		findByPageSql.WriteString("@@@@_@@@@")
		for _, val := range findByPageParam.Gorders {
			findByPageSql.WriteString(",")
			findByPageSql.WriteString(val.String())
		}
	} else {
		if !strings.Contains(defaultOrderSql.String(), " ORDER BY ") {
			findByPageSql.WriteString(" ORDER BY ")
		}

		findByPageSql.WriteString(defaultOrderSql.String())
	}

	if findByPageParam.Gpage.GiSize < 1 {
		findByPageParam.Gpage.GiSize = 10
	}

	if findByPageParam.Gpage.GiCurrent < 1 {
		findByPageParam.Gpage.GiCurrent = 1
	}

	findByPageSql.WriteString(" LIMIT ")
	findByPageSql.WriteString(strconv.Itoa((findByPageParam.Gpage.GiCurrent - 1) * findByPageParam.Gpage.GiSize))
	findByPageSql.WriteString(" , ")
	findByPageSql.WriteString(strconv.Itoa(findByPageParam.Gpage.GiSize))

	result1 := findByPageSql.String()

	result1 = strings.Replace(result1, "${sDbName}", sDbName, -1)
	result1 = strings.Replace(result1, "${sTableName}", sTableName, -1)
	result1 = strings.Replace(result1, "@@@@_@@@@ OR ", "", -1)
	result1 = strings.Replace(result1, "@@@@_@@@@, ", "", -1)
	result1 = strings.Replace(result1, "ORDER BY @@@@_@@@@,", "ORDER BY ", -1)
	result1 = strings.Replace(result1, " ORDER BY @@@@_@@@@ LIMIT ", " LIMIT ", -1)
	result1 = strings.Replace(result1, " WHERE  AND ", " WHERE ", -1)
	result1 = strings.Replace(result1, " WHERE AND ", " WHERE ", -1)

	return result0, result1, params
}

func (mu ModuleUtil) GetFindByPageSelectSqlByField(dataInfo DataInfo, sTableName, sFieldName string, oTherJoin map[string]string) (string, string) {
	var appendFieldSql strings.Builder
	var dictionarySql strings.Builder

	//--发现关联表--//
	if (sTableName != dataInfo.GsTableName) && ("" != dataInfo.GsRelName) && ("" != dataInfo.GsRelMainName) {
		title := strings.TrimSpace(dataInfo.GsRelTitle)
		if "" == title {
			title = sFieldName
		}

		appendFieldSql.WriteString(" ")
		appendFieldSql.WriteString(dataInfo.GsTableName)
		appendFieldSql.WriteString("_")
		appendFieldSql.WriteString(dataInfo.GsRelName)
		appendFieldSql.WriteString(".")
		appendFieldSql.WriteString(dataInfo.GsName)
		appendFieldSql.WriteString(" AS ")
		appendFieldSql.WriteString(title)
		appendFieldSql.WriteString(",")

		var leftJoinName strings.Builder
		leftJoinName.WriteString(dataInfo.GsTableName)
		leftJoinName.WriteString("_")
		leftJoinName.WriteString(dataInfo.GsRelName)

		_, ok := oTherJoin[leftJoinName.String()]
		if ok { //已经存在
			return appendFieldSql.String(), dictionarySql.String()
		}

		var leftJoin strings.Builder
		leftJoin.WriteString(" LEFT JOIN ")
		leftJoin.WriteString(SqlFactory{}.GetDbName(dataInfo.GsDbName))
		leftJoin.WriteString(dataInfo.GsTableName)
		leftJoin.WriteString(" AS ")
		leftJoin.WriteString(leftJoinName.String())
		leftJoin.WriteString(" ON (")
		leftJoin.WriteString(dataInfo.GsTableName)
		leftJoin.WriteString("_")
		leftJoin.WriteString(dataInfo.GsRelName)
		leftJoin.WriteString(".")
		leftJoin.WriteString(dataInfo.GsRelName)
		leftJoin.WriteString(" = ")
		leftJoin.WriteString(SqlFactory{}.GetDbName(dataInfo.GsDbName))
		leftJoin.WriteString(sTableName)
		leftJoin.WriteString(".")
		leftJoin.WriteString(dataInfo.GsRelMainName)
		leftJoin.WriteString(") ")

		oTherJoin[leftJoinName.String()] = leftJoin.String() //防止重复累加相同的关联

		dictionarySql.WriteString(leftJoin.String())

		return appendFieldSql.String(), dictionarySql.String()
	}

	//--检查备注中的通用关联--//
	sComment := StringUtil{}.SubBetween(dataInfo.GsComment, "(", ")", true)
	if "" == sComment {
		return appendFieldSql.String(), dictionarySql.String()
	}

	if strings.HasPrefix(sComment, "枚举") { //枚举类型
		sComment = sComment[len("枚举")+1:]
		comment := strings.Split(sComment, ",")
		if len(comment) < 1 {
			return appendFieldSql.String(), dictionarySql.String()
		}

		appendFieldSql.WriteString(" CASE ")
		appendFieldSql.WriteString(dataInfo.GsTableName)
		appendFieldSql.WriteString(".")
		appendFieldSql.WriteString(dataInfo.GsName)

		for _, val := range comment {
			array := strings.Split(val, ":")
			if len(array) < 1 {
				return appendFieldSql.String(), dictionarySql.String()
			}

			if len(array) < 2 {
				array = append(array, "缺失")
			}

			appendFieldSql.WriteString(" WHEN ")
			appendFieldSql.WriteString(array[0])
			appendFieldSql.WriteString(" THEN '")
			appendFieldSql.WriteString(array[1])
			appendFieldSql.WriteString("' ")
		}

		appendFieldSql.WriteString(" ELSE '未知' END AS s")
		appendFieldSql.WriteString(dataInfo.GsName[1:])
		appendFieldSql.WriteString("Text,")

		return appendFieldSql.String(), dictionarySql.String()
	}

	if strings.HasPrefix(sComment, "布尔值,") { //布尔值
		sComment = sComment[len("布尔值,"):]
		comment := strings.Split(sComment, ";")
		if len(comment) < 0 {
			return appendFieldSql.String(), dictionarySql.String()
		}

		appendFieldSql.WriteString(" CASE ")
		appendFieldSql.WriteString(sTableName)
		appendFieldSql.WriteString(".")
		appendFieldSql.WriteString(dataInfo.GsName)

		for _, val := range comment {
			val = strings.TrimSpace(val)
			if "" == val {
				return appendFieldSql.String(), dictionarySql.String()
			}

			array := strings.Split(val, ":")
			if len(array) < 1 {
				return appendFieldSql.String(), dictionarySql.String()
			}

			if len(array) < 2 {
				array = append(array, "缺失")
			}

			appendFieldSql.WriteString(" WHEN ")
			appendFieldSql.WriteString(array[0])
			appendFieldSql.WriteString(" THEN '")
			appendFieldSql.WriteString(array[1])
			appendFieldSql.WriteString("' ")
		}

		appendFieldSql.WriteString(" ELSE '否' END AS s")
		appendFieldSql.WriteString(dataInfo.GsName[1:])
		appendFieldSql.WriteString("Text,")

		return appendFieldSql.String(), dictionarySql.String()
	}

	if strings.HasPrefix(sComment, "字典") { //字典
		appendFieldSql.WriteString(" Dictionary_")
		appendFieldSql.WriteString(dataInfo.GsName)
		appendFieldSql.WriteString(".")
		appendFieldSql.WriteString(TableTreeNodeName)
		appendFieldSql.WriteString(" AS s")
		appendFieldSql.WriteString(dataInfo.GsName[1:])
		appendFieldSql.WriteString("Text,")

		dictionarySql.WriteString(" LEFT JOIN ")
		dictionarySql.WriteString(SqlFactory{}.GetDbName(GBaseSystemName))
		dictionarySql.WriteString(TableNameDictionary)
		dictionarySql.WriteString(" AS Dictionary_")
		dictionarySql.WriteString(dataInfo.GsName)
		dictionarySql.WriteString(" ON (Dictionary_")
		dictionarySql.WriteString(dataInfo.GsName)
		dictionarySql.WriteString(".")
		dictionarySql.WriteString(TableOnlyignName)
		dictionarySql.WriteString(" LIKE '")
		dictionarySql.WriteString(dataInfo.GsName)
		dictionarySql.WriteString("%' AND Dictionary_")
		dictionarySql.WriteString(dataInfo.GsName)
		dictionarySql.WriteString(".")
		dictionarySql.WriteString(TableDictionaryValueName)
		dictionarySql.WriteString(" = CAST(")
		dictionarySql.WriteString(sTableName)
		dictionarySql.WriteString(".")
		dictionarySql.WriteString(dataInfo.GsName)
		dictionarySql.WriteString(" AS CHAR)) ")

		return appendFieldSql.String(), dictionarySql.String()
	}

	return appendFieldSql.String(), dictionarySql.String()
}

/**
 * 取对应模块业务实体
 * object 对象
 */
func (mu ModuleUtil) GetSimplName(object interface{}) string {
	name := reflect.TypeOf(object).String()

	iSt := strings.Index(name, ".")
	if iSt > -1 {
		name = name[iSt+1:]
	}

	return name
}

/**
 * 取对应模块业务模糊查询控制时间限制
 * moduleName 控制层
 */
func (mu ModuleUtil) GetLikeTimeLimit(object interface{}) int {
	moduleName := mu.GetSimplName(object)
	if strings.HasSuffix(moduleName, "Controller") {
		moduleName = moduleName[:(len(moduleName) - 10)]
	}

	iLikeTimeLimit := GlobalVariable{}.Get(moduleName + "_LikeTimeLimit") //模糊查询时是否要进行时间范围限制,默认限制7天内
	if nil == iLikeTimeLimit {
		return 7 //如果没有设置, 直接默认限制7天内
	}

	return iLikeTimeLimit.(int)
}
